﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using WSS.Models.Test;
using WSS.Pub;

/*
 * 本类拷自 WSS.BLL.User.UserImport.cs
 * 稍微修改
 */

namespace WSS.BLL.Test
{
    public class TestImport
    {
        /// <summary>
        /// 导入文件的物理路径
        /// </summary>
        private string _FILE_PHYSICAL_PATH { get; set; }
        /// <summary>
        /// 文件名，把文件名当作试卷名
        /// </summary>
        private string _FILE_NAME { get; set; }

        /// <summary>
        /// 要更新到XT_XHB的值 TEST_QUESTION 表
        /// </summary>
        private int _LATEST_TEST_QUESTION_ID { get; set; }
        /// <summary>
        /// 要更新到XT_XHB的值 TEST_ANSWER 表
        /// </summary>
        private int _LATEST_TEST_ANSWER_ID { get; set; }
        private string _UPLOADER_ID { get; set; }

        List<DBState> _LIST_DBSTATE = new List<DBState>();

        /// <summary>
        /// 导入文件转成的 DataTabel
        /// </summary>
        private DataTable _XLS_CONCTENT { get; set; }

        public TestImport(string filename, string uploader_id)
        {
            var import_path = Utils.AppConfigHelper.GetValue("Uploadify_SaveTo");
            import_path += "/" + filename;
            _FILE_PHYSICAL_PATH = System.Web.HttpContext.Current.Server.MapPath(import_path);

            if (!System.IO.File.Exists(_FILE_PHYSICAL_PATH))
            {
                throw new Exception("文件在不存在");
            }

            _UPLOADER_ID = uploader_id;

            System.IO.FileInfo fi = new FileInfo(_FILE_PHYSICAL_PATH);
            _FILE_NAME = fi.Name.Replace(fi.Extension, "");

            if (fi.Extension.ToUpper() == ".XLSX")
            {
                _XLS_CONCTENT = Utils.XlsxHelper.XlsxToDataTabel(_FILE_PHYSICAL_PATH);
            }
            else
            {
                _XLS_CONCTENT = Utils.XlsHelper.XlsToDataTabel(_FILE_PHYSICAL_PATH);
            }


            _CheckColHead();
            _CheckContent();
            _Import();
        }


        private string get_blue_html(string val)
        {
            return "<span style='color:blue;'>" + val + "</span>";
        }


        private void _CheckColHead()
        {
            string[] arr_header = new string[] { "题目标题", "难度等级", "正确答案" };

            DataColumnCollection row = _XLS_CONCTENT.Columns;
            for (int i = 0; i < 3; i++)
            {
                if (row[i].ColumnName == arr_header[i])
                {
                    continue;
                }
                throw new Exception("导入文件的表头验证失败，请下载模板，并严格按照模板导入");
            }
        }

        private void _CheckContent()
        {
            if (_XLS_CONCTENT.Rows.Count == 0)
            {
                throw new Exception("您上传的是空白文件");
            }

            List<string> listerror = new List<string>();

            string test_id = BLL.Xt.XhbManager.Instance.GetXh("TEST_TEST");
            string question_id = BLL.Xt.XhbManager.Instance.GetXh("TEST_QUESTION");
            string answer_id = BLL.Xt.XhbManager.Instance.GetXh("TEST_ANSWER");

            int qid = int.Parse(question_id) + 20;
            int aid = int.Parse(answer_id) + 20;

            TEST_TEST main_test = new TEST_TEST();

            main_test.CATE_NO = "";
            main_test.FLAG_INVALID = 0;
            main_test.ORDER_NO = test_id;
            main_test.READCOUNT = 0;
            main_test.TEST_CONTENTS = "..";
            main_test.TEST_ID = test_id;
            main_test.TEST_LEVEL = "1";
            main_test.TEST_NAME = _FILE_NAME;
            main_test.TEST_YEAR = DateTime.Now.Year.ToString();
            main_test.UPLOAD_TIME = DateTime.Now;
            main_test.UPLOAD_USERID = _UPLOADER_ID;

            _LIST_DBSTATE.Add(new DBState { Name = main_test.MAP_INSERT, Param = main_test, Type = ESqlType.INSERT });

            for (int i = 0; i < _XLS_CONCTENT.Rows.Count; i++)
            {
                DataRow dr = _XLS_CONCTENT.Rows[i];

                bool haswrong = false;
                string err = "第" + get_blue_html((i + 1).ToString()) + "行: ";

                string rightanswer = Pub.Utils.GetString(dr["正确答案"]);
                if (rightanswer.IsNullOrEmpty())
                {
                    haswrong = true;
                    err += get_blue_html("[正确答案]列必须得有值");
                }
                if (!dr["难度等级"].IsNumeric())
                {
                    haswrong = true;
                    err += get_blue_html("[难度等级]列只允许为数字");
                }

                TEST_QUESTION ques = new TEST_QUESTION();

                ques.CATE_NO = "";
                ques.FLAG_INVALID = 0;
                ques.QUESTION_ANALYSIS = "";
                ques.QUESTION_CONTENTS = "";
                ques.QUESTION_ID = (qid++).ToString();

                ques.QUESTION_LEVEL = dr["难度等级"].IsNumeric() ? int.Parse(Pub.Utils.GetString(dr["难度等级"])) : 1;

                ques.QUESTION_NO = (i).ToString();
                ques.QUESTION_TITLE = Pub.Utils.GetString(dr["题目标题"]);
                ques.QUESTION_TYPE = rightanswer.Length == 1 ? 1 : rightanswer.Length > 1 ? 2 : 1;
                ques.TEST_ID = test_id;


                // 循环试题选项============================
                DataColumnCollection cols = _XLS_CONCTENT.Columns;
                for (int j = 3; j < cols.Count; j++)
                {
                    DataColumn column = cols[j];

                    string optiontext = Pub.Utils.GetString(dr[column.ColumnName]);
                    if (optiontext.IsNullOrEmpty())
                    {
                        continue;
                    }

                    TEST_ANSWER answer = new TEST_ANSWER();
                    answer.ANSWER_ID = (aid++).ToString();
                    answer.ANSWER_NO = column.ColumnName.Replace("选项", "").Trim();
                    answer.CONTENTS = optiontext;
                    answer.DETAILS = "none";
                    answer.FLAG_INVALID = 0;
                    answer.FLAG_ISRIGHT = rightanswer.IndexOf(answer.ANSWER_NO) != -1 ? 1 : 0;
                    answer.QUESTION_ID = ques.QUESTION_ID;
                    _LIST_DBSTATE.Add(new DBState { Name = answer.MAP_INSERT, Param = answer, Type = ESqlType.INSERT });
                }
                // 循环试题选项============================

                if (!haswrong)
                {
                    _LIST_DBSTATE.Add(new DBState
                    {
                        Name = ques.MAP_INSERT,
                        Param = ques,
                        Type = ESqlType.INSERT
                    });
                }
                else
                {
                    listerror.Add(err);
                }
            }

            string msg = "";
            foreach (string err in listerror)
            {
                msg += "<li class='list-group-item'>" + err + "</li>";
            }
            if (msg != "")
            {
                throw new Exception(msg);
            }
            _LATEST_TEST_ANSWER_ID = aid;
            _LATEST_TEST_QUESTION_ID = qid;
        }

        private void _Import()
        {
            BLL.Xt.XhbManager.Instance.SetXh("TEST_QUESTION", _LATEST_TEST_QUESTION_ID);
            BLL.Xt.XhbManager.Instance.SetXh("TEST_ANSWER", _LATEST_TEST_ANSWER_ID);
            DB.Execute(_LIST_DBSTATE);
        }
    }
}